package com.atguigu.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zhangqiang
 * @since 2022-09-07
 */
@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public RetVal login(@RequestBody UserInfo uiUserInfo, HttpServletRequest request) {
        //1.根据用户账号和密码查询数据库
        UserInfo dbUserInfo=userInfoService.queryUserFromDb(uiUserInfo);
        if (dbUserInfo != null) {
            //2.生成一个token给前端
            HashMap<String, Object> retMap = new HashMap<String, Object>();
            String token = UUID.randomUUID().toString();
            retMap.put("token",token);
            //返回用户信息给前端页面
            String nickName = dbUserInfo.getNickName();
            retMap.put("nickName",nickName);
            //3.把用户信息放入redis中 user:login:token
            String userKey= RedisConst.USER_LOGIN_KEY_PREFIX+token;
            JSONObject userInfoJson = new JSONObject();
            userInfoJson.put("userId",dbUserInfo.getId());
            userInfoJson.put("loginIp", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(userKey,userInfoJson,RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retMap);
        }else {
            return RetVal.fail().message("登录失败");
        }
    }

    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request){
        //删除redis 拼接redis
        String token=request.getHeader("token");
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if("token".equals(cookie.getName())){
//                token=cookie.getValue();
//            }
//        }
        String userKey=RedisConst.USER_LOGIN_KEY_PREFIX+token;
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }

}

